package com.git.hui.yinshua.biz.util;

import cn.hutool.core.img.ColorUtil;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 图片封装工具类
 *
 * @author YiHui
 * @date 2024/6/17
 */
public class ImgUtil {

    public static List<String> toImgList(String imgs) {
        if (imgs == null) {
            return new ArrayList<>();
        }

        return Splitter.on(",http").splitToStream(imgs).filter(StringUtils::isNotBlank)
                .map(s -> s.startsWith("http") ? s : ("http" + s))
                .collect(Collectors.toList());
    }

    public static String toImgs(List<String> imgList) {
        if (CollectionUtils.isEmpty(imgList)) {
            return "";
        }

        return Joiner.on(",").join(imgList);
    }

    public static String getImgBgColor(String img) {
        try {
            BufferedImage bufferedImage = ImageIO.read(new URL(img));
            return ColorUtil.getMainColor(bufferedImage);
        } catch (IOException e) {
            return "#ffffff";
        }
    }
}
